<!-- 新闻动态 -->
<template>
  <div class="news">
    <div class="search-wrap">
      <a-row
        type="flex"
        justify="space-between"
      >
        <a-col
          :span="7"
          class="display-flex align-items-center"
        >
          <span class="m-r-10 w-50 text-align-right">关键词</span>
          <a-input
            placeholder="编号/标题"
            style="width:260px"
            v-model="queryParam.search"
          />
        </a-col>
        <a-col
          :span="7"
          class="display-flex align-items-center"
        >
          <span class="m-r-10 w-50 text-align-right">作者</span>
          <a-input
            placeholder="请输入作者名称"
            style="width:260px"
            v-model="queryParam.author"
          />
        </a-col>
        <a-col :span="7">
          <a-button
            class="m-r-30 m-l-30"
            type="primary"
            @click="onSearch"
          >
            检索
          </a-button>
          <a-button @click="reset">
            重置
          </a-button>
        </a-col>
      </a-row>
      <a-row class="m-t-36 p-r-10">
        <a-col>
          <a-button
            type="primary"
            @click="createNew"
          >
            新建
          </a-button>
        </a-col>
      </a-row>
    </div>
    <div class="table-wrap m-t-30">
      <template>
        <s-table
          ref="sTable"
          size="default"
          :rowKey="record => record.id"
          :columns="columns"
          :data="loadData"
        >
          <span
            slot="subtitle"
            slot-scope="text"
          >
            <span v-if="$filters.textWidth(text) > 400">
              <a-tooltip
                placement="top"
                :title="text"
              >
                <span style="cursor: pointer;width: 400px; display: inline-block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
                  {{text}}
                </span>
              </a-tooltip>
            </span>
            <span v-else>{{text}}</span>
          </span>
          <span
            slot="action"
            slot-scope="text, record"
          >
            <a @click="edit(record.id)">修改</a>
            <a-divider type="vertical" />
            <a-popconfirm
              placement="top"
              ok-text="确定"
              cancel-text="取消"
              @confirm="deleteNew(record.id)"
            >
              <template slot="title">
                <span>您确定删除么？</span>
              </template>
              <a>删除</a>
            </a-popconfirm>
          </span>
        </s-table>
      </template>
    </div>
    <a-modal
      width="900px"
      :title="title"
      :visible="visible"
      @ok="handleOk"
      @cancel="visible = false"
    >
      <div class="section">
        <a-form-model
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-form-model-item
            label="标题"
            prop="title"
          >
            <a-input
              v-model="form.title"
              placeholder="≤100位有效字符"
            />
          </a-form-model-item>
          <a-form-model-item
            label="封面"
            prop="coverImg"
          >
            <a-upload
              name="cover"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :customRequest="uploadPicCustom"
            >
              <img
                style="width:102px;height:102px;"
                v-if="form.coverImg"
                :src="form.coverImg"
                alt="cover"
              />
              <div v-else>
                <a-icon :type="loading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">
                  上传
                </div>
              </div>
            </a-upload>
          </a-form-model-item>
          <a-form-model-item
            label="添加时间"
            prop="createTime"
          >
            <a-date-picker
              v-model="form.createTime"
              style="width:100%;"
              valueFormat="YYYY-MM-DD"
            />
          </a-form-model-item>
          <a-form-model-item
            label="作者"
            prop="author"
          >
            <a-input
              v-model="form.author"
              placeholder="≤50位有效字符"
            />
          </a-form-model-item>
          <a-form-model-item
            label="文本"
            prop="content"
          >
            <editor-bar
              v-model="form.content"
              :isClear="isClear"
            ></editor-bar>
          </a-form-model-item>
          <a-form-model-item label="附件">
            <a-upload
              :customRequest="uploadCustom"
              :file-list="form.attachmentList"
              :multiple="true"
              @change="uploadChange"
            >
              <a-button>
                <a-icon type="upload" /> 上传文件
              </a-button>
            </a-upload>
          </a-form-model-item>

        </a-form-model>
      </div>
    </a-modal>
  </div>
</template>

<script>
import EditorBar from '@/components/wangEnduit'
const columns = [
  {
    title: "序号",
    dataIndex: "sort",
    key: "sort"
  },
  {
    title: "编号",
    dataIndex: "code",
    key: "code"
  },
  {
    title: "标题",
    key: "title",
    dataIndex: "title",
    scopedSlots: { customRender: "subtitle" }
  },
  {
    title: "添加时间",
    key: "createTime",
    dataIndex: "createTime"
  },
  {
    title: "作者",
    key: "author",
    dataIndex: "author"
  },
  {
    title: "操作",
    key: "action",
    scopedSlots: { customRender: "action" }
  }
];

function getBase64 (img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
export default {
  name: 'news',
  data () {
    return {
      title: '新增',
      columns,
      newId: '',
      visible: false,
      defaultFileList: [],
      isClear: false,
      loading: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
      form: {
        attachmentList: [],
        author: "", //作者
        content: "", //文本内容
        coverImg: "", //封面图片
        createTime: "", //添加时间
        level: undefined, //级别
        title: "" //标题
      },
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" },
        { max: 100, message: "请输入≤100位有效字符", trigger: "change" }],
        level: [{ required: true, message: "请选择级别", trigger: "change" }],
        createTime: [
          { required: true, message: "请选择添加时间", trigger: "change" }
        ],
        // coverImg: [{ required: true, message: "请上传封面", trigger: "change" }],
        author: [{ required: true, message: "请选择作者", trigger: "blur" },
        { max: 500, message: "请输入≤50位有效字符", trigger: "change" }],
        content: [{ required: true, message: "请输入文本", trigger: "blur" }]
      },
      // 查询条件参数
      queryParam: {
        author: "", //作者
        search: "" //搜索内容
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return this.$axios({
          url: "/news/list",
          cancel: {
            _self: this
          },
          method: "get",
          params: Object.assign(parameter, this.queryParam)
        }).then(res => {
          return {
            data: res.data.newsList,
            totalCount: res.data.total,
            pageNo: res.data.curPage
          };
        });
      }
    };
  },
  components: {
    EditorBar
  },
  methods: {
    onSearch () {
      this.$refs.sTable.refresh(true);
    },
    reset () {
      this.queryParam = {
        author: "", //作者
        search: "" //搜索内容
      };
    },
    onChange () { },
    //修改通知公告
    handleOk () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          let method = null
          const data = {
            attachmentList: this.form.attachmentList,
            author: this.form.author,
            content: this.form.content,
            createTime: this.form.createTime,
            coverImg: this.form.coverImg,
            title: this.form.title,
          }
          if (this.title === '新增') {
            method = 'post'
          } else {
            method = 'put'
            data.id = this.newId
          }
          this.$axios({
            url: '/news',
            method: method,
            loadingEl: '.ant-modal-content',
            cancel: {
              _self: this
            },
            data: data
          }).then(res => {
            this.$refs.ruleForm.resetFields()
            this.$refs.sTable.refresh()
            this.visible = false;
            this.$message.success(this.title + '成功')
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    //新建
    createNew () {
      this.visible = true;
      this.title = "新增";
      this.form = {
        attachmentList: [],
        author: "", //作者
        content: "", //文本内容
        coverImg: "", //封面图片
        createTime: "", //添加时间
        level: undefined, //级别
        title: "" //标题
      }
    },
    edit (id) {
      this.visible = true
      this.title = "修改"
      this.newId = id
      this.$axios({
        url: "/news/detail",
        method: "get",
        loadingEl: '.ant-modal-content',
        cancel: {
          _self: this
        },
        params: {
          id
        }
      }).then(res => {
        let attachmentList = (res.data.attachmentList || []).map(list => {
          list.uid = list.id
          list.url = list.filePath
          return list
        })
        this.form = {
          ...res.data,
          attachmentList
        }
      });
    },
    //删除新闻
    deleteNew (id) {
      this.$axios({
        url: "/news",
        method: "delete",
        loadingEl: this.$el,
        cancel: {
          _self: this
        },
        params: {
          id
        }
      }).then(res => {
        this.$refs.sTable.refresh();
      });
    },
    //上传封面
    uploadPicCustom (file, fileList) {
      this.loading = true
      this.$uploadFile(info, {
        cancel: {
          _self: this
        },
        validateType: 'cover'
      }).then(res => {
        this.loading = false
        this.form.coverImg = res.url
      })
    },

    //上传附件
    uploadCustom (info) {
      this.$uploadFile(info, {
        loadingEl: '.ant-modal-content',
        title: '上传中,请稍等。。。',
        cancel: {
          _self: this
        },
        validateType: 'attachment'
      }).then(res => {
        this.form.attachmentList.push({
          url: res.url,
          name: res.name
        })
      })
    },
    //上传文件改变
    uploadChange (info) {
      let file = info.file
      let index = this.form.attachmentList.findIndex(list => list.filePath === file.url)
      this.form.attachmentList.splice(index, 1);
    },
  }
}

</script>
<style scoped lang='less'>
</style>